﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Navigation;
using CeskyRozhlasWP8.Model;
using CeskyRozhlasWP8.Resources;
using CeskyRozhlasWP8.ViewModel;
using Microsoft.Phone.BackgroundAudio;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.WindowsAzure.MobileServices;
using WP8BackgroundPlaybackAgent;

namespace CeskyRozhlasWP8.View
{


    public partial class MainPage : PhoneApplicationPage
    {
        readonly MainPageViewModel _mainPageVm = new MainPageViewModel();

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            DataContext = _mainPageVm;
            //Semi-manual localization :)
            //For the application bar, there is no way to localize properly, due to "text cannot be empty" error
            //((ApplicationBarIconButton)ApplicationBar.Buttons[0]).Text = AppResources.SearchPageTitle;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).Text = AppResources.DownloadsListMenuItemText;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).Text = AppResources.SettingsMenuItemText;
        }



        // Load data for the ViewModel Items
        protected override async void OnNavigatedTo(NavigationEventArgs navigationArgs)
        {
            //Just for the case, if we are already playing a station since previous invocation - we can detect it and skip the main page
            //Navigate straight to the currently played station page.
            if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing && navigationArgs.NavigationMode == NavigationMode.New)
            {
                NavigateToStation(AudioPlayer.ExtractStationId(BackgroundAudioPlayer.Instance.Track));
            }
            try
            {
                MainPivot.Visibility = Visibility.Visible;
                WeakConnectionWarning.Visibility = Visibility.Collapsed;
                
                foreach (var item in await ShowsData.Instance.GetAllGroups())
                {
                    _mainPageVm.Groups.Add(new StationsGroup { UniqueId = item.Id, Title = item.Title });
                }
                //RefreshGroupContent is not needed to call here. It should be called from Pivot_Loaded
                //await RefreshGroupContent(_mainPageVm.Groups.FirstOrDefault());
            }
            catch (MobileServiceInvalidOperationException)
            {
                //MainPivot.Visibility = Visibility.Collapsed;
                WeakConnectionWarning.Visibility = Visibility.Visible;
            }
        }

        private async Task RefreshGroupContent(StationsGroup stationsGroup)
        {
            var items = await ShowsData.Instance.GetStationPreviewByGroupId(stationsGroup.UniqueId);
            //TODO: do it smarter, if possible - find a simpler way to copy something into the observable collection
            stationsGroup.Items.Clear();
            foreach (var item in items)
            {
                if (string.IsNullOrEmpty(item.Title))
                {
                    item.Title = "-";
                }
                //Avoid duplicates.
                //Duplicates become possible because of "sub-show" feed, 
                //like "vecerni radiozurnal 7-9PM" and "zelena vlna 7:00-7:05PM" are intersecting 
                //and look like duplicates in the current view
                if (stationsGroup.Items.All(station => station.Id != item.Id))
                {
                    stationsGroup.Items.Add(item);
                }
            }
        }

        private void NavigateToStation(int id)
        {
            NavigationService.Navigate(new Uri("/RadiostationPage.xaml?autoPlay=false&stationid=" + id, UriKind.Relative));
        }

        private async Task RefreshPivot(int i, Microsoft.Phone.Controls.PivotItem item)
        {
            await RefreshGroupContent(_mainPageVm.Groups[i]);
        }

        private async void Pivot_LoadingPivotItem(object sender, PivotItemEventArgs eventArgs)
        {
            var myPivotControl = sender as Microsoft.Phone.Controls.Pivot;
            if (myPivotControl != null && eventArgs.Item != null)
            {
                await RefreshPivot(myPivotControl.SelectedIndex, myPivotControl.SelectedItem as PivotItem);
            }
        }

        private void HledatMenuItemClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SearchPage.xaml", UriKind.Relative));
        }

        private void NastaveniMenuItemClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
        }
        private void RecordingMenuItemClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/RecordingPlanPage.xaml", UriKind.Relative));
        }

        private void Grid_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var aUiElement = sender as FrameworkElement;
            if (aUiElement != null)
            {
                var aStationInfo = aUiElement.DataContext as PlayingNow;
                if (aStationInfo != null)
                {
                    NavigateToStation(aStationInfo.Id);
                }
            }
        }


        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}


        //IEnumerable<BackgroundTransferRequest> _requestCache = null;
        //private void RefreshBindings()
        //{
        //    // Dispose of the old cache to stop memory leaks
        //    if (_requestCache != null)
        //    {
        //        foreach (var request in _requestCache)
        //        {
        //            // Clean up the cache to prevent leaks
        //            request.TransferProgressChanged -=
        //                request_TransferProgressChanged;
        //            request.TransferStatusChanged -= request_TransferStatusChanged;
        //            request.Dispose();
        //        }
        //    }
        //    // Get the Updated Requests
        //    _requestCache = BackgroundTransferService.Requests;

        //    // Wire up the events
        //    foreach (var request in _requestCache)
        //    {
        //        request.TransferProgressChanged +=
        //          request_TransferProgressChanged;
        //        request.TransferStatusChanged += request_TransferStatusChanged;
        //    }
        //}

        //private void request_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        //{
        //    // Update the Page
        //    RefreshBindings();
        //}

        //private void request_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        //{
        //    // Limited to 5 requests
        //    // So remove it when it's done
        //    if (e.Request.TransferStatus == TransferStatus.Completed)
        //    {
        //        if (BackgroundTransferService.Find(e.Request.RequestId) != null)
        //        {
        //            BackgroundTransferService.Remove(e.Request);
        //        }
        //        e.Request.Dispose();
        //    }

        //    // Update the Page
        //    RefreshBindings();
        //}

    }
}